package cn.edu.scau.cmi.dengshixin.orm.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.dengshixin.orm.domain.Student;
import cn.edu.scau.cmi.dengshixin.orm.hibernate.SessionFactoryUtil;

public class StudentDao {
	
	private static final Logger log = LoggerFactory.getLogger(StudentDao.class);
	public static final String NAME = "name";
	private Session session;
	
	
	public Session getSession() {
		session = SessionFactoryUtil.getSession();
		return session;
	}
	
	public void save(Student stu) {
		log.debug("saving Student instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.save(stu);
			transaction.commit();
			log.debug("save successful");
		} 
		catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	public void delete(Student instance) {
		log.debug("deleting Student instance");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.delete(instance);
			transaction.commit();
			log.debug("delete successful");
		}
		catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}
	
	public void update(Student instance) {
		log.debug("updating Student");
		try {
			getSession();
			Transaction transaction = session.beginTransaction();
			session.update(instance);
			transaction.commit();
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	
	public List findAll() {
		log.debug("finding all student");
		try {
			String queryStr = "from Student";
			Query queryObject = getSession().createQuery(queryStr);
			log.debug("find by property successful");
			return queryObject.list();
		}
		catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
}
